package com.xinbochuang.machine.framework.security.custom;

import cn.hutool.json.JSONUtil;
import com.xinbochuang.machine.common.constant.Constants;
import com.xinbochuang.machine.common.domain.LoginUser;
import com.xinbochuang.machine.common.utils.ServletUtils;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import com.xinbochuang.machine.framework.web.service.TokenService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份证号认证成功
 *
 * @author 黄晓鹏
 * @date 2020-09-14 12:03
 */
@Component
public class SuccessAuthenticationHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Resource
    private TokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws ServletException, IOException {
        AjaxResult json = AjaxResult.ok();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        String token = tokenService.createToken(loginUser);
        json.put(Constants.TOKEN, token);
        json.put(Constants.DATA, loginUser.getUser());
        ServletUtils.renderString(response, JSONUtil.toJsonStr(json));
    }
}
